package licode.unisop.auth.application.executor;

import cn.hutool.core.codec.Base64;
import com.google.code.kaptcha.Producer;
import licode.unisop.auth.client.api.CodeValidateService;
import licode.unisop.auth.client.vo.CaptchaVO;
import licode.unisop.provider.api.SiCacheProvider;
import licode.unisop.types.AuthConst;
import licode.unisop.types.CacheConf;
import licode.unisop.types.util.IdGenUtil;
import licode.unisop.unilite.result.UniException;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 实现验证码接口
 *
 * @author licode
 * @version 1.0
 * @date 2018-05-01 16:52
 */
@Primary
@Component
public class CodeValidateServiceDef implements CodeValidateService {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Resource
    private SiCacheProvider siCacheProvider;

    @Resource
    private CaptchaSetting captchaSetting;

    @Override
    public CaptchaVO buildCaptcha() {
        CaptchaVO result = new CaptchaVO();
        boolean captchaEnabled = captchaSetting.getEnabled();

        if (!captchaEnabled) {
            return result;
        }

        // 保存验证码信息
        String uuid = IdGenUtil.buildSimpleId();
        String verifyKey = CacheConf.CAPTCHA_PREFIX + uuid;

        String capStr;
        String code = null;
        BufferedImage image = null;

        String captchaType = captchaSetting.getType();
        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        siCacheProvider.set(verifyKey, code, AuthConst.CAPTCHA_EXPIRATION);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            throw new UniException(-1, e.getMessage());
        }

        result.setKey(uuid);
        result.setImage( Base64.encode(os.toByteArray()));

        return result;
    }

    @Override
    public void checkCaptcha(String uuid, String code) {
        if (StringUtils.isEmpty(code)) {
            throw new UniException(-1, "验证码不能为空");
        }

        if (StringUtils.isEmpty(uuid)) {
            throw new UniException(-1, "验证码已失效");
        }

        String verifyKey = CacheConf.CAPTCHA_PREFIX + uuid;
        String captcha = siCacheProvider.get(verifyKey);
        siCacheProvider.delete(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new UniException(-1, "验证码错误");
        }
    }
}
